package com.zhou.project.modules.system.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhou.project.components.base.service.BaseService;
import com.zhou.project.modules.system.user.dao.SysUserDao;
import com.zhou.project.modules.system.user.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author zhouhonggang
 * @version 1.0.0
 * @project spring-boot-project
 * @datetime 2021/8/11 13:42
 * @description: 用户逻辑层
 */
@Service
public class SysUserService extends BaseService<SysUserDao, SysUser> implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 用户注册
     *
     * @param entity 用户对象
     */
    @Transactional
    public void insert(SysUser entity) {
        //密码加密
        entity.setPassword(passwordEncoder.encode(entity.getPassword()));
        //插入数据
        baseMapper.insert(entity);
    }

    /**
     * 根据登陆账号获取用户
     *
     * @param account 登陆账号
     * @return 登陆用户
     */
    public SysUser getUserByAccount(String account) {
        //绑定查询参数
        QueryWrapper<SysUser> wrapper = new QueryWrapper<SysUser>().eq("account", account);
        //执行数据库查询
        return baseMapper.selectOne(wrapper);
    }

    /**
     * 多条件分页查询
     *
     * @param entity 参数
     * @return 分页对象
     */
    public Page<SysUser> page(SysUser entity) {
        //封装动态查询参数
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        //姓名精确查询
        if (StringUtils.hasLength(entity.getName())) {
            wrapper.like("name", entity.getName());
        }
        //启用状态查询
        if (!ObjectUtils.isEmpty(entity.getLocked())) {
            wrapper.eq("locked", entity.getLocked());
        }
        //昵称模糊查询
        if (StringUtils.hasLength(entity.getNick())) {
            wrapper.like("nick", entity.getNick());
        }
        //注册时间区间查询
        if (!ObjectUtils.isEmpty(entity.getDates())) {
            wrapper.between("created_time", entity.getDates()[0], entity.getDates()[1]);
        }
        //按照注册日期排序
        wrapper.orderByAsc("created_time");
        //封装分页查询参数
        return baseMapper.selectPage(Page.of(entity.getCurrent(), entity.getSize()), wrapper);
    }

    /**
     * 根据登录账号查询密码
     * @param username 登录正好
     * @return 用户对象 （账号密码）
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //封装查询参数
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("account", username);
        SysUser sysUser = baseMapper.selectOne(wrapper);

        //根据查询结果返回spring-security状态
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new UsernameNotFoundException("很遗憾，账号不存在");
        } else if (sysUser.getLocked() == 1) {
            throw new LockedException("很遗憾，账号已被锁定");
        } else if (sysUser.getDeleteFlag() == 1) {
            throw new DisabledException("很遗憾，账号已被删除");
        }

        //根据账号查询权限列表
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();

        //封装用户权限列表
        baseMapper.queryPermissionsCodeByAccount(username).forEach(code->{
            authorities.add(new SimpleGrantedAuthority(code));
        });

        return new User(username, sysUser.getPassword(), authorities);
    }
}
